import {LoginInput} from "@/components/input/LoginInput.tsx";
import userIcon from "@/assets/icons/user.png";
import passIcon from "@/assets/icons/pass.png"
import {Button, Form} from "antd";
import { useCallback } from "react";
import style from "@/styles/login.module.scss"
import type {LoginStateType} from "@/types/loginType.ts";
import {systemApi} from "@/services/system.ts";
import {useNavigate} from "react-router";
import type {FormRules} from "@/types/commonType.ts";

const {Item, useForm} = Form

const rules: FormRules<LoginStateType> = {
    userName: [
        {
            required: true,
            message: '请输入账号'
        }
    ],
    passWord: [
        {
            required: true,
            message: '请输入密码'
        }
    ]
}

export const LoginForm = () => {
    const [form] = useForm()

    const navigate = useNavigate()

    const onFinish = useCallback((e: LoginStateType) => {
        systemApi.passLogin(e).then(res => {
            sessionStorage.setItem('token', res.data.token)
            sessionStorage.setItem('user', JSON.stringify(res.data.user))
            navigate('/select', {
                replace: true,
            })
        })
    }, [])

    return (
        <Form
            form={form}
            onFinish={onFinish}
        >
            <Item name={'userName'} rules={rules.userName}>
                <LoginInput
                    before={
                        <img src={userIcon} alt=""/>
                    }
                />
            </Item>

            <Item name={'passWord'} rules={rules.passWord}>
                <LoginInput
                    before={
                        <img src={passIcon} alt=""/>
                    }
                />
            </Item>

            <Item>
                <div className={style.loginBtn}>
                    <Button size={'large'} color={'cyan'} type={'primary'} variant={'solid'} htmlType={'submit'}>登录</Button>
                </div>
            </Item>
        </Form>
    )
}